package com.controller;

import com.entity.Result;
import com.entity.User;
import com.service.UserService;
import com.utils.HttpUtil;
import com.utils.MapUtil;
import com.utils.ResultUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("")
public class MainController extends BaseController {

    @Autowired
    private UserService userService;


    @RequestMapping("admin/login")
    public String adminLogin(HttpServletRequest request) {
         User user = (User)request.getSession().getAttribute("user");
         if (user == null){
             return "/admin/login";
         }else{
             return "/admin/index";
        }
    }


    @RequestMapping("login")
    @ResponseBody
    public Result login(User user, HttpServletRequest request, Integer type) {

        User user1 = userService.selectOneModel(putEntityInMap(user));
        if (user1 != null) {
            request.getSession().setAttribute("user", user1);
          return ResultUtil.success(user1);
        } else {
            return ResultUtil.error("账号或密码错误!");
        }
    }


    @RequestMapping("welcome")
    public String welcome(HttpServletRequest request) {

        return "/admin/welcome";
    }

    @RequestMapping("logout")
    public String loout(HttpServletRequest request) {
        request.getSession().invalidate();
        return "/admin/login";
    }

    @RequestMapping("register")
    public String regUser() {
        return "/admin/register";
    }




    @RequestMapping("reg")
    @ResponseBody
    public Result reguser(HttpServletRequest request, User user, Integer type) {
        String username = user.getUsername();
        User oneModel = userService.selectOneModel(MapUtil.buildMap("username", username));
        if(oneModel != null){
            return ResultUtil.error("用户已被占用！");
        }
        user.preInsert();
        int i = userService.insertModel(user);
        if (i == 0) {
            return ResultUtil.error("失败");
        } else {
            return ResultUtil.success(null);
        }
    }

    public static void main(String[] args) {

    }
}
